from django.shortcuts import render
from django.views import View
from goods.models import SKU
from django.http import HttpResponseForbidden, JsonResponse
import json
from django_redis import get_redis_connection
from utils.response_code import RETCODE
from users.views import LoginRequiredMixinJosn
from django.contrib.auth.mixins import LoginRequiredMixin



class CartsView(LoginRequiredMixin,View):
    def get(self , request):
        user = request.user
        redis_conn = get_redis_connection('carts')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        redis_selected = redis_conn.smembers('selected_%s' % user.id)

        cart_dict = {}
        for sku_id , count in redis_cart.items():
            cart_dict[int(sku_id)] = {
                'count': int(count),
                'selected': sku_id in redis_selected
            }


        skus_id = cart_dict.keys()
        sku_data = SKU.objects.filter(id__in=skus_id)
        cart_list = []
        for sku in sku_data:
            cart_skus_dict = {
                'id': sku.id,
                'name': sku.name,
                'price': str(sku.price),
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
                'default_image_url': str(sku.default_image)
            }
            cart_list.append(cart_skus_dict)


        context = {'cart_skus': cart_list}
        return render(request, 'cart.html', context=context)

    # 加入购物车
    def post(self , request):

        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected' , True)

        try:
            SKU.objects.get(id=sku_id)
        except Exception:
            return HttpResponseForbidden("商品参数有误")

        user = request.user

        redis_conn = get_redis_connection('carts')
        # user_id = {sku_id:count}
        redis_conn.hincrby('cart_%s' % user.id, sku_id, count)
        if selected:
            # 结果为 True ， 勾选的进行保存
            redis_conn.sadd('selected_%s' % user.id, sku_id)

        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


    # 更新数据
    def put(self , request):
        data = json.loads(request.body.decode())
        # 商品ID
        sku_id = data.get('sku_id')
        # 数量
        count = data.get('count')
        # 是否勾选
        selected = data.get('selected', True)

        # 校验商品是否存在
        try:
            sku_data = SKU.objects.get(id=sku_id)
        except Exception:
            return HttpResponseForbidden("商品参数有误")

        # 获得用户信息
        user = request.user

        # 修改数据库中的数据
        redis_conn = get_redis_connection('carts')
        redis_conn.hset('cart_%s' % user.id, sku_id, count)
        if selected:
            redis_conn.sadd('selected_%s' % user.id, sku_id)
        else:
            redis_conn.srem('selected_%s' % user.id, sku_id)



        cart_skus_dict = {
            'id': sku_data.id,
            'name': sku_data.name,
            'price': sku_data.price,
            'count': count,
            'selected': selected,
            'amount': count * sku_data.price,
            'default_image_url': str(sku_data.default_image)
        }


        return JsonResponse({'code':RETCODE.OK , 'errmsg':"OK" , 'cart_sku':cart_skus_dict})


    # 删除数据
    def delete(self , request):
        data = json.loads(request.body.decode())
        # 商品ID
        sku_id = data.get('sku_id')
        user = request.user

        redis_conn = get_redis_connection('carts')
        redis_conn.hdel('cart_%s' % user.id, sku_id)
        redis_conn.srem('selected_%s' % user.id, sku_id)
        return JsonResponse({'code': RETCODE.OK, 'errmsg': "OK"})



class CartSelectView(View):
    def put(self , request):
        data = json.loads(request.body.decode())
        select = data.get('selected')

        user = request.user
        redis_conn = get_redis_connection('carts')
        # 获取到该用户的所有购物车商品
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        redis_sku_id = redis_cart.keys()

        # 全选商品
        if select:
            redis_conn.sadd('selected_%s' % user.id, *redis_sku_id)
        else:
            for sku_id in redis_sku_id:
                redis_conn.srem('selected_%s' % user.id, sku_id)

        return JsonResponse({
            'code':RETCODE.OK,
            'errmsg':'OK'
        })






